﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Text;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Openfree.Framework.DataAccess;
using ICSS.Office.Word;
using System.Collections.Generic;
using ICSS.Office.Core;

public partial class TaskDispatch : PMSBase
{

    private string cmdText = @"select a.TaskCode,a.TaskItemID,a.TaskID,a.SNYear,a.SNGroup,a.SNTask,a.SNProject,a.SNDispatch,a.TaskState,D.CodeName as GroupName,C.Guest,C.Phone,C.Location,C.RoomNo,C.HouseNo,C.TroubleDescription,C.IsRequestGood,C.CreateDate,case when B.status='" + PMSGoodsState.NotOut + "' then '" + PMSGoodsState.GetName("" + PMSGoodsState.NotOut) + @"' when B.status='" + PMSGoodsState.IsOut + "' then '" + PMSGoodsState.GetName("" + PMSGoodsState.IsOut) + @"' else '----' end ReqStatus, (select Username from T_User where UserID=C.UserID) UserName,(select Subject from T_OrgTree where OrgID=C.OrgID) as OrgName from PMS_TaskItem a 
                   left join IC_Requisition B on B.TaskID=a.TaskItemID left join PMS_TaskLX C on c.TaskID = a.TaskID left join T_CodeConfig D on D.CodeValue=a.SNGroup AND D.Category = '" + PMSCodeCategory.PMS_BMZB + "' where 1=1 ";
     
    protected void Page_Load(object sender, EventArgs e)
    {
        if (ViewState["Request.UrlReferrer"] == null)
        {
            ViewState["Request.UrlReferrer"] = Request.UrlReferrer.AbsolutePath;
        }
        this.TableName = "PMS_TaskLX";
        this.Key = "TaskID";
        if ((!string.IsNullOrEmpty(Request["isgroup"]) && Convert.ToBoolean(Request["isgroup"])) || hfIsGroup.Value == "true")
        {
            hfIsGroup.Value = "true";
            cmdText = cmdText + " and a.SNGroup='" + SessionManager.UserGroupCode + "' ";
        }
        if (!IsPostBack)
        {
            FillGirdView(0, cmdText + " and C.TaskState='0' order by a.TaskState asc,C.CreateDate desc");
            if (!string.IsNullOrEmpty(Request["TaskItemID"]))
            {
                this.btnView_Click(null, e);
            } 
            tbPersonCode.Attributes.Add("onkeypress", "Openfree.prototype.EnterSubmit('" + tbPersonCode.ClientID + "',event);");
        }
        else
        {

            if (pnlEdit.Visible && !string.IsNullOrEmpty(tbPersonCode.Text))
            {
                TaskPersonItem.AddSelectPerson(tbPersonCode.Text);
                tbPersonCode.Text = "";
            }
            else if (pnlGrid.Visible)
                FillGirdView(this.gridView.SplitPageIndex, string.Empty);
 
        }
    }
    public void btnSearchPerson_Click(object sender, EventArgs e)
    {
        pnlSearchPerson.Visible = true;
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        StringBuilder sql = new StringBuilder(cmdText); 
        if (!string.IsNullOrEmpty(S_Guest.Text))
        {
            sql.Append(" AND C.Guest like '%").Append(S_Guest.Text).Append("%'");
        }
        if (!string.IsNullOrEmpty(S_Phone.Text))
        {
            sql.Append(" AND C.Phone = '").Append(S_Phone.Text).Append("'");
        }
        if (!string.IsNullOrEmpty(S_TaskState.SelectedValue))
        {
            sql.Append(" AND a.TaskState = '").Append(S_TaskState.SelectedValue).Append("'");
        }
        sql.Append(" order by a.TaskState asc,C.CreateDate desc");
        FillGirdView(0, sql.ToString());
    }
    protected void FillGirdView(int currentPage, string cmdText)
    {
        if (string.IsNullOrEmpty(cmdText))
        {
            cmdText = ViewState[this.ClientID + "cmdText"].ToString();
        }
        ViewState[this.ClientID + "cmdText"] = cmdText;
        SqlSplitPage splitPage = new SqlSplitPage(base.Connection, cmdText);
        splitPage.PageSize = 10;
        DataSet ds = splitPage.LoadDataSet(currentPage);
        gridView.ShowFooter = true;
        gridView.NavigationData = splitPage.GetNavigationData(currentPage);
        gridView.DataSource = ds.Tables[0];
        gridView.DataBind();
    } 

    protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex == 0)
            {
                (e.Row.Cells[0].Controls[2] as LiteralControl).Text =
                    "<input id=\"TaskItemID\" checked=\"checked\" name=\"TaskItemID\" type=\"radio\" value=\'" + ((HiddenField)e.Row.Cells[0].Controls[3]).Value + "\' />";
            }
            else
            {
                (e.Row.Cells[0].Controls[2] as LiteralControl).Text =
                    "<input id=\"TaskItemID\" name=\"TaskItemID\" type=\"radio\" value=\'" + ((HiddenField)e.Row.Cells[0].Controls[3]).Value + "\' />";
            }
            ((HyperLink)e.Row.Cells[1].Controls[0]).NavigateUrl = "TaskDispatch.aspx?isgroup=" + hfIsGroup.Value + "&TaskItemID=" + ((HiddenField)e.Row.Cells[0].Controls[3]).Value;
            e.Row.Cells[8].Text = PMSTaskState.GetName(e.Row.Cells[8].Text);
            e.Row.Cells[7].Text = string.IsNullOrEmpty(e.Row.Cells[7].Text)? "": Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy-MM-dd HH:mm");
        }
    }

    protected void gridView_SplitPageIndexChange(object sender, CommandEventArgs e)
    {
        FillGirdView(Int32.Parse(e.CommandArgument.ToString()), ViewState[this.ClientID + "cmdText"].ToString());
    }

    private void ClearValue()
    {
        tbGuest.Text = "";
        tbRoomNo.Text = "";
        cbHouseNo.Text = "";
        tbPhone.Text = "";
        tbTroubleDescription.Text = "";
        lbUserID.Text = SessionManager.LoginName;
        lbOrgID.Text = SessionManager.OrgName;
        cbIsReqGood.Checked = false;
        pnlSearchPerson.Visible = false;
        lbCreateDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
    }

    protected void btnView_Click(object sender, EventArgs e)
    {
        string TaskItemID = Request.Form["TaskItemID"];
        if(sender==null)
            TaskItemID = Request["TaskItemID"];
        if (string.IsNullOrEmpty(TaskItemID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }

        hfAddOrEdit.Value = "View";
        hfTaskItemID.Value = TaskItemID;

        DataSet ds = PMSAccess.GetDataSet(this.Connection, cmdText + " and a.TaskItemID='" + TaskItemID + "'");
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow row = ds.Tables[0].Rows[0];
        ClearValue();
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        btnSelect.Visible = false;
        btnSave.Visible = false;
        btnSearchPerson.Visible = false; 

        //显示领单人
        InitGridReceiverView(TaskItemID);

        SessionManager.DataSet = PMSAccess.GetDataSet(this.Connection, "select * from PMS_TaskItem where TaskItemID='" + TaskItemID + "'", "PMS_TaskItem");
        //GoodItemOut.IsReadOnly = true;
       // GoodItemOut.InitData("IC_RequisitionItem", "RequisitionItemID", "TaskID", hfTaskItemID.Value);
        //获取是否已经派发人员，固定一个小组
        DataSet tempds = PMSAccess.GetDataSet(this.Connection, "select * from PMS_TaskItem where TaskID='" + TaskItemID + "'");
        string groupcode = string.Empty;
        if (tempds != null && tempds.Tables[0].Rows.Count > 0)
        {
            groupcode = tempds.Tables[0].Rows[0]["SNGroup"].ToString();
        }
        TaskPersonItem.ShowWorkTime = false;
        TaskPersonItem.IsReadOnly = true;
        TaskPersonItem.InitData("TaskID", hfTaskItemID.Value, groupcode);
        UserAccess user = new UserAccess(base.Connection);
        tbGuest.Text = row["Guest"].ToString();
        tbRoomNo.Text = row["RoomNo"].ToString();
        cbHouseNo.Text = row["HouseNo"].ToString();
        tbPhone.Text = row["Phone"].ToString();
        tbTroubleDescription.Text = row["TroubleDescription"].ToString();
        lbOrgID.Text = row["OrgName"].ToString();
        lbUserID.Text = row["UserName"].ToString();
        cbIsReqGood.Checked = (row["IsRequestGood"]!=null&&row["IsRequestGood"]!=DBNull.Value)?Convert.ToBoolean(row["IsRequestGood"]):false;
        lbCreateDate.Text = Convert.ToDateTime(row["CreateDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
    }
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        ifdown.Attributes["src"] = string.Empty;
        tipMessage1.ShowMessage("", 5000);

        string TaskItemID = Request.Form["TaskItemID"];
        if (string.IsNullOrEmpty(TaskItemID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        
        hfAddOrEdit.Value = "Edit";
        hfTaskItemID.Value = TaskItemID;

        DataSet ds = PMSAccess.GetDataSet(this.Connection, cmdText + " and a.TaskItemID='" + TaskItemID + "'");
        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow row = ds.Tables[0].Rows[0];
        if (Convert.ToInt32(row["TaskState"]) == PMSTaskState.Complete)
        {
            Alert("您选择的任务已经完成，不能再进行操作！");
            return;
        }
        else if (Convert.ToInt32(row["TaskState"]) == PMSTaskState.IsRemove)
        {
            Alert("您选择的任务已经作废，不能再进行操作！");
            return;
        }
        ClearValue();
        pnlGrid.Visible = false;
        pnlEdit.Visible = true;
        btnSelect.Visible = true;
        btnSave.Visible = true;
        btnSearchPerson.Visible = true; 

        //显示领单人
        InitGridReceiverView(TaskItemID);

        SessionManager.DataSet = PMSAccess.GetDataSet(this.Connection, "select * from PMS_TaskItem where TaskItemID='" + TaskItemID + "'", "PMS_TaskItem");
        //GoodItemOut.InitData("IC_RequisitionItem", "RequisitionItemID", "TaskID", hfTaskItemID.Value);
        //获取是否已经派发人员，固定一个小组
        DataSet tempds = PMSAccess.GetDataSet(this.Connection, "select * from PMS_TaskItem where TaskID='" + TaskItemID + "'");
        string groupcode = string.Empty;
        if(tempds!=null&& tempds.Tables[0].Rows.Count>0)
        {
            groupcode = tempds.Tables[0].Rows[0]["SNGroup"].ToString();
        }
        TaskPersonItem.ShowWorkTime = false;
        TaskPersonItem.InitData("TaskID", TaskItemID, groupcode); 
        UserAccess user = new UserAccess(base.Connection);
        tbGuest.Text = row["Guest"].ToString();
        tbRoomNo.Text = row["RoomNo"].ToString();
        cbHouseNo.Text = row["HouseNo"].ToString();
        tbPhone.Text = row["Phone"].ToString();
        tbTroubleDescription.Text = row["TroubleDescription"].ToString();
        lbOrgID.Text = row["OrgName"].ToString();
        lbUserID.Text = row["UserName"].ToString();
        cbIsReqGood.Checked = (row["IsRequestGood"] != null && row["IsRequestGood"] != DBNull.Value) ? Convert.ToBoolean(row["IsRequestGood"]) : false;
        lbCreateDate.Text = Convert.ToDateTime(row["CreateDate"].ToString()).ToString("yyyy-MM-dd HH:mm"); 
    } 
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        string taskID = Request.Form["TaskItemID"];
        if (string.IsNullOrEmpty(taskID))
        {
            base.Alert("请选择一条记录");
            FillGirdView(this.gridView.SplitPageIndex, string.Empty);
            return;
        }
        string cmdText = "select * from PMS_TaskItem where TaskItemID='{0}'";
        cmdText = string.Format(cmdText, taskID);

        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);

        if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
        {
            Alert("您选择的记录已经被删除，请刷新数据！");
            return;
        }
        DataRow row = ds.Tables[0].Rows[0];
        if (Convert.ToInt32(row["TaskState"]) == PMSTaskState.Complete)
        {
            Alert("您选择的任务已经完成，不能再进行作废操作！");
            return;
        }
        else if (Convert.ToInt32(row["TaskState"]) == PMSTaskState.IsRemove)
        {
            Alert("您选择的任务已经作废，不能再进行操作！");
            return;
        }

        cmdText = "update PMS_TaskItem set TaskState='" + PMSTaskState.IsRemove + "' where TaskItemID='" + taskID + "'";
        BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
        tipMessage1.ShowMessage("作废操作成功", 5000); 
//        return;
//        cmdText = @"delete from PMS_TaskItem where TaskItemID='{0}';
//                        delete from PMS_TaskUser where TaskID='{0}';
//                        delete from IC_RequisitionItem where RequisitionID in (select RequisitionID from IC_Requisition where TaskID='{0}');
//                        delete from IC_Requisition where TaskID='{0}';";
//        cmdText = string.Format(cmdText, taskID);
//        BaseAccess.ExecuteNonQuery(base.Connection, cmdText);
//        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }
    protected void btnDocument_Click(object sender, EventArgs e)
    {
        string taskID = hfTaskItemID.Value;
        string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString() + ".doc");
        string outinfo = DocumentHelper.ExportDispatchDocument(PMSConst.PMSDispatchDocTemplatePath, filePath, taskID);
        if (string.IsNullOrEmpty(outinfo))
        {
            ifdown.Attributes["src"] = "../SiteAdmin/DownLoadHandler.ashx?url=" + 
                filePath + "&name=" + HttpUtility.UrlEncode("派工单.") + DateTime.Now.ToString("MMdd.HHmmss") + ".doc";
            //base.DownLoadFile(Server.MapPath(filePath), "派工单.doc");
        }
        else
        {
            tipMessage1.ShowMessage(outinfo, 5000); 
        }
    }

    

    protected void btnSave_Click(object sender, EventArgs e)
    {
        //if (hfAddOrEdit.Value == "Edit")
        {
            DataTable dt = null;
            //string str = SessionManager.GetValue(PMSConst.m_TableItemName).ToString();

            //判断是否选择派修人员
            string result = TaskPersonItem.PreProcessSave();
            if (!string.IsNullOrEmpty(result))
            {
                tipMessage1.ShowMessage(result, 5000);
                return;
            } 
            //判断是否配备物料:如果有则添加一个领料申请单
            //result = GoodItemOut.PreProcessSave();
            //如果选择了物料格式不正确提示信息，没有选择物料不验证
            //if (GoodItemOut.SelectItemsCount > 0 && !string.IsNullOrEmpty(result))
            //{
            //    tipMessage1.ShowMessage(result, 5000);
            //    return;
            //}
            StringBuilder str = new StringBuilder();
            if (SessionManager.DataSet.Tables.Contains(TaskPersonItem.m_TableName))
            {
                dt = SessionManager.DataSet.Tables[TaskPersonItem.m_TableName];
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    str.Append(",'").Append(dr["UserID"].ToString()).Append("'");
                    dr["TaskID"] = hfTaskItemID.Value;
                    dr["UserType"] = PMSCodeCategory.UserWorker;
                    dr["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    dr["UpdateUser"] = SessionManager.UserID;
                }
            }
            if (SessionManager.DataSet.Tables.Contains("PMS_TaskItem"))
            {
                foreach (DataRow dr in SessionManager.DataSet.Tables["PMS_TaskItem"].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) 
                        continue;
                    dr["TaskState"] = PMSTaskState.Dispatch;
                }
            } 
            //if (GoodItemOut.SelectItemsCount > 0 && SessionManager.DataSet.Tables.Contains(str))
            //{
            //    if (SessionManager.DataSet.Tables[GoodItemOut.m_ReqTableName].Rows.Count > 0)
            //    {
            //        string guid = System.Guid.NewGuid().ToString();
            //        DataRow req_dr = SessionManager.DataSet.Tables[GoodItemOut.m_ReqTableName].Rows[0];
            //        PMSAccess.AppendValue(ref req_dr, EnumOperator.EDIT);
            //        dt = SessionManager.DataSet.Tables[str];
            //        foreach (DataRow dr in dt.Rows)
            //        {
            //            if (dr.RowState != DataRowState.Deleted)
            //            {
            //                dr["UpdateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            //                dr["UpdateUser"] = SessionManager.UserID;
            //            }
            //        }
            //    }
            //    else
            //    {
            //        string guid = System.Guid.NewGuid().ToString();
            //        DataRow req_dr = SessionManager.DataSet.Tables[GoodItemOut.m_ReqTableName].NewRow();
            //        req_dr["RequisitionID"] = guid;
            //        req_dr["TaskID"] = hfTaskItemID.Value;
            //        req_dr["Status"] = PMSGoodsState.NotOut;
            //        req_dr["RequisitionType"] = PMSCodeCategory.PMS_RCLX;
            //        req_dr["RequisitionCode"] = PMSAccess.GetCode(EnumCodeKind.LingLiao);
            //        req_dr["RequisitionUser"] = SessionManager.Username;
            //        req_dr["RequisitionDate"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            //        PMSAccess.AppendValue(ref req_dr, EnumOperator.ADD);
            //        SessionManager.DataSet.Tables[GoodItemOut.m_ReqTableName].Rows.Add(req_dr);

            //        dt = SessionManager.DataSet.Tables[str];
            //        foreach (DataRow dr in dt.Rows)
            //        {
            //            if (dr.RowState != DataRowState.Deleted)
            //            {
            //                dr["RequisitionID"] = guid;
            //                dr["CreateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
            //                dr["CreateUser"] = SessionManager.UserID;
            //            }
            //        }
            //    }
            //} 
            //PMSAccess.UpdateDataSet(this.Connection, new string[] { "PMS_TaskItem", "IC_Requisition", "IC_RequisitionItem", "PMS_TaskUser"}, SessionManager.DataSet);
            PMSAccess.UpdateDataSet(this.Connection, new string[] { "PMS_TaskItem", "PMS_TaskUser" }, SessionManager.DataSet);

            if (str.Length > 0)
            {
                PMSAccess.ExecuteNonQuery(this.Connection, "update PMS_User set IsWorking=IsWorking+1 where UserId in (" + str.Remove(0, 1).ToString() + ")");
            }
            tipMessage1.ShowMessage("任务派发成功", 5000); 
        } 

        this.btnDocument_Click(sender, e);
        this.btnCancel_Click(sender, e);
        LoadPage();
        
    }

    private void LoadPage()
    {
        if (ViewState["Request.UrlReferrer"] != null &&
            ViewState["Request.UrlReferrer"].ToString().IndexOf("TaskNewAccept.aspx") > 0)
        {
            //从受理页面进来的，并不是点击菜单直接进入到当前页面的，这样的操作可以自动跳转回受理页面
            string script = "<script>var time=20; function loadpage() { document.getElementById('spanTime').innerHTML=time+'秒钟后自动返回受理页面';  time=time-1; if(time==0) this.location = \"TaskNewAccept.aspx{0}\"; setTimeout(loadpage, 1000) }\r\n setTimeout(loadpage, 1000);</script>";
            if (hfIsGroup.Value == "true")
            {
                script = script.Replace("{0}", "?isgroup=true");
            }
            else
            {
                script = script.Replace("{0}", "");
            }
            this.ClientScript.RegisterStartupScript(this.GetType(), "goback", script);
        }
    }

    protected void btnPreTabsMenu_Click(object sender, EventArgs e)
    {

    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        pnlGrid.Visible = true;
        pnlEdit.Visible = false;
        FillGirdView(this.gridView.SplitPageIndex, string.Empty);
    }

    protected void btnSelect_Click(object sender, EventArgs e)
    {
        if (TaskPersonItem.OnSelect != null)
        {
            TaskPersonItem.IsReadOnly = false;
            TaskPersonItem.OnSelect(sender, e);
            TaskPersonItem.SetGroupReadOnly(hfCurrentGroupCode.Value);
        }
    }
    protected void btnSelectGood_Click(object sender, EventArgs e)
    {
        //if (GoodItemOut.OnSelect != null)
        //    GoodItemOut.OnSelect(sender, e);
    }

    #region 显示领单人信息 
    protected void InitGridReceiverView(string taskId)
    {
        string cmdItemsText = @"SELECT T.*,A.Username,A.GroupCode,A.Mobile,B.OrgID,D.Subject as OrgName,C.CodeName as GroupName  FROM PMS_TaskUser T inner join PMS_User A on A.UserID = T.UserID 
                    left join T_OrgUser B on B.UserID = T.UserID 
                    left join  T_CodeConfig C on C.CodeValue=A.GroupCode  AND C.Category = '" + PMSCodeCategory.PMS_BMZB + @"' 
                    left join T_OrgTree D on D.OrgID=B.OrgID where 1=1 and T.UserType='" + PMSCodeCategory.UserReceiver + "' and T.TaskID='" + taskId + "'";

        DataSet ds = PMSAccess.GetDataSet(this.Connection, cmdItemsText);
        if (ds.Tables[0].Rows.Count > 0)
        {
            hfCurrentGroupCode.Value = ds.Tables[0].Rows[0]["GroupCode"].ToString();
        }
        gridReceiverView.DataSource = ds.Tables[0];
        gridReceiverView.ShowFooter = false;
        gridReceiverView.DataBind();
    }
    #endregion

}
